/*jslint sloppy: true */
/*global require */
var angular = require('angular'),
	probe = require('../global');
require('./task.html');
probe.controller('Task', function ($scope, ocDI, ocDialog, LC, Task, Case, simulight, $location, $log) {
	var ciList, isSuccess, isRunning, bootArgs = $location.search();
	$scope.ciHEAD = null;

	// toobar on the top.
	$scope.newTask = function () {
		$scope.task = new Task({
			name: '新建测试任务',
			version: $scope.project.version,
			draft: true
		});
		$scope.schemas = {
			object: null,
			caseList: [], // {name: string, code: string, caseId: number},...
			config: { /* times: 1, screen: auto */ }
		};
	};
	$scope.createTask = function () {
		var t = $scope.task;
		t.schemas = angular.toJson($scope.schemas);
		t.draft = true;
		t.$create();
	};
	$scope.updateTask = function () {
		var t = $scope.task;
		t.schemas = angular.toJson($scope.schemas);
		t.$modify();
	};

	$scope.caseStatus = [];
	$scope.openTask = function (task) {
		var t = $scope.task = task;
		t.$get(null, function () {
			$location.search('taskId', t.taskId);
			var schemas = angular.fromJson(t.schemas),
				caseReqs = [],
				caseList = [];

			if (!t.draft) { delete t.taskId; }
			t.version = $scope.project.version;
			$scope.schemas = schemas;
			angular.forEach(schemas.caseList, function (c, index) {
				caseReqs.push(c.caseId);
				schemas.caseList[index] = c.caseId;
			});
			if (!caseReqs.length) { return; }

			caseList = Case.query({
				list: caseReqs.join()
			}, function () {
				var caseMap = {},
					newCaseList = [];

				$scope.task = t;

				angular.forEach(caseList, function (c) {
					caseMap[c.caseId] = {
						name: c.name,
						caseId: c.caseId,
						code: c.code,
						comment: c.comment
					};
				});

				angular.forEach(schemas.caseList, function (caseId, index) {
					var $c = caseMap[caseId];
					if ($c) {
						newCaseList.push(angular.copy(caseMap[caseId]));
					}
				});

				schemas.caseList = newCaseList;
			});
		});
	};
	$scope.jumpToCase = function ($c) {
		$location.search('caseId', $c.caseId);
		$scope.setMode('case');
	};

	// toolbar in task editor panel
	$scope.caseCtrl = { selected: -1 };
	$scope.selectCase = function (i, e) {
		e.stopPropagation();
		$scope.caseCtrl.selected = i;
	};
	function exchange(arr, key1, key2) {
		var t = arr[key1];
		arr[key1] = arr[key2];
		arr[key2] = t;
	}
	$scope.deleteCase = function (i) {
		$scope.caseCtrl.selected -= 1;
		$scope.schemas.caseList.splice(i, 1);
	};
	$scope.up = function (i) {
		exchange($scope.schemas.caseList, i, i - 1);
		$scope.caseCtrl.selected -= 1;
	};
	$scope.down = function (i) {
		exchange($scope.schemas.caseList, i, i + 1);
		$scope.caseCtrl.selected += 1;
	};
	$scope.trash = function () {
		$scope.caseStatus = [];
		$scope.schemas.caseList = [];
	};
	$scope.shuffle = function () {
		$scope.schemas.caseList.sort(function () {
			return Math.random() - 0.5;
		});
	};

	// Task runtime.
	LC.setup({
		successCallback: function (CASE) {
			if (!isRunning) { return; }
			$scope.caseStatus[$scope.caseCtrl.selected] = isSuccess;
			$scope.ciHEAD = ciList[$scope.caseCtrl.selected += 1];

			if ($scope.ciHEAD) {
				isSuccess = true;
				$scope.ciHEAD.start();
			} else {
				ocDialog.alert({
					title: '运行结束',
					message: '如果没有问题，您现在可以将它创建为正式任务'
				}, ocDI);
				$scope.mask = false;
				ciList = [];
				$scope.ciHEAD = null;
			}

		},
		triggerCallback: function (element) {
			simulight(element, $scope.LCF);
		},
		runExceptionHandle: function (CASE) {
			isSuccess = false;
		}
	});

	ciList = [];
	function compileAll() {
		try {
			angular.forEach($scope.schemas.caseList, function (c) {
				ciList.push(new LC.Case(LC.parse(c.code), {}));
			});
		} catch (e) {
			$log.error('[probe > task > compile]');
			$log.error(e);
		}
	}
	$scope.runTask = function () {
		$scope.caseStatus = [];
		$scope.caseCtrl.selected = 0;
		compileAll();
		$scope.ciHEAD = ciList[$scope.caseCtrl.selected].start();
		$scope.mask = true;
		isSuccess = true;
		isRunning = true;
	};
	$scope.stopTask = function () {
		$scope.ciHEAD.stop();
		isRunning = false;
		$scope.ciHEAD = null;
		$scope.mask = false;
		ciList = [];
	};


	//init
	if (bootArgs.taskId) {
		$scope.task = $scope.openTask(new Task({ taskId: bootArgs.taskId}));
	} else {
		$scope.newTask();
	}
	$scope.$on('$destroy', function () {
		if ($scope.ciHEAD) { $scope.stopTask(); }
	});
});
